import java.util.LinkedList;
import java.util.Queue;

class Solution {
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};
    int m, n;

    public void solve(char[][] board) {
        m = board.length;
        n = board[0].length;

        // 从边界开始，标记所有与边界相连的 'O' 为 '#'
        for (int i = 0; i < m; i++) {
            if (board[i][0] == 'O') bfs(board, i, 0);
            if (board[i][n - 1] == 'O') bfs(board, i, n - 1);
        }
        for (int j = 0; j < n; j++) {
            if (board[0][j] == 'O') bfs(board, 0, j);
            if (board[m - 1][j] == 'O') bfs(board, m - 1, j);
        }

        // 遍历整个矩阵，将未被标记的 'O' 修改为 'X'，将 '#' 恢复为 'O'
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                } else if (board[i][j] == '#') {
                    board[i][j] = 'O';
                }
            }
        }
    }

    private void bfs(char[][] board, int i, int j) {
        Queue<int[]> q = new LinkedList<>();

        q.add(new int[]{i, j});
        board[i][j] = '#'; // 标记为特殊字符

        while (!q.isEmpty()) {
            int[] curr = q.poll();
            int x = curr[0];
            int y = curr[1];

            for (int k = 0; k < 4; k++) {
                int nx = x + dx[k];
                int ny = y + dy[k];
                if (nx >= 0 && nx < m && ny >= 0 && ny < n && board[nx][ny] == 'O') {
                    q.add(new int[]{nx, ny});
                    board[nx][ny] = '#'; // 标记为特殊字符
                }
            }
        }
    }
}